<?php
import('libs.bdd.AbstractSql');
import('libs.bdd.mysql.MySqlRessource');
/**
 * Classe Sql.
 * Permet d'interagir avec la base de données
 * @author Gaetan Collaud
 */
class MySql extends AbstractSql
{
	/** Infos de connexion */
	private $conInfos = array();

	public function __construct($host, $user, $pass, $bdd) {
		$this->boolSupport = false;
		$this->conInfos = array($host, $user, $pass, $bdd);
	}

	private function connect(){
		if(!$this->connect){
			$deb = microtime(true);

			$this->connect = mysql_connect($this->conInfos[0], $this->conInfos[1], $this->conInfos[2]);
			if ($this->connect) {
				$this->bdd = mysql_select_db($this->conInfos[3],$this->connect);
				if (!$this->bdd) {
					mysql_close($this->connect);
					$this->connect = false;
					Log::err(__METHOD__, 'Impossible de selectionner une base de donnees.');
				}
				mysql_query('SET NAMES "utf8"');
			}else
				Log::err(__METHOD__, 'Impossible de se connecté à la base de donnée.');

			$this->addTime(microtime(true)-$deb, 'connect');
		}
	}

	public function close() {
		$deb = microtime(true);

		if($this->connect) {
			$this->connect = mysql_close($this->connect);
			$return = $this->connect;
		}else
			$return = false;

		$this->addTime(microtime(true)-$deb, 'close');

		return $return;
	}

	public function query($query, $fetch_array = false) {
		$this->connect();
		$deb = microtime(true);

		if($this->connect) {
			$ret = mysql_query($query, $this->connect)or user_error($query.' '.mysql_errno($this->connect).' : '.mysql_error($this->connect));
			$res = new MySqlRessource($ret);
			++$this->nbr_queries;
			if($fetch_array) {
				$res = $res->fetch();
				if(!$res) Log::notice(__METHOD__, 'erreur mysql_fetch_assoc pour la requte : '.$query);
			}
		}else
			Log::err(__METHOD__, 'La requête SQL est vide.');

		$this->addTime(microtime(true)-$deb);

		return $res;
	}

	public function exec($query) {
		$this->connect();
		$deb = microtime(true);

		if($this->connect) {
			$ret = mysql_unbuffered_query($query, $this->connect)or user_error($query.' '.mysql_errno($this->connect).' : '.mysql_error($this->connect));
			++$this->nbr_queries;
		}else
			Log::err(__METHOD__, 'La requête SQL est vide.');

		$this->addTime(microtime(true)-$deb);

		return true;
	}

	public function lastInsertId(){
		return mysql_insert_id($this->connect);
	}

	static public function escape($t){
		return Base::getSql()->escapeCallBack($t);
	}

	public function escapeCallBack($t){
		$this->connect();
		return mysql_real_escape_string($t, $this->connect);
	}
}
?>